package model

import (
	"appengine"
	"appengine/datastore"
	"appengine/memcache"
	"entity"
)

var TagPool_CacheName string = "_tagPool_"

func AddTag(c appengine.Context, obj entity.Tag) error {
	key := datastore.NewKey(c, "Tag", obj.Alias, 0, nil)
	_, err := datastore.Put(c, key, &obj)
	if err != nil {
		return err
	}
	return nil
}

func AddTagRelationship(c appengine.Context, obj entity.TagRelationship) error {
	key := datastore.NewKey(c, "TagRelationship", obj.ID, 0, nil)
	_, err := datastore.Put(c, key, &obj)
	if err != nil {
		return err
	}
	return nil
}

func DeleteTag(c appengine.Context, id string) error {
	var cacheTitle string = "_tag" + id
	key := datastore.NewKey(c, "Tag", id, 0, nil)
	if err := datastore.Delete(c, key); err != nil {
		return err
	} else {
		memcache.Delete(c, cacheTitle)
		memcache.Delete(c, TagPool_CacheName)
		return nil
	}
}

func GetTag(c appengine.Context, id string, obj *entity.Tag) error {
	var cacheTitle string = "_tag" + id
	if _, err := memcache.Gob.Get(c, cacheTitle, &obj); err == memcache.ErrCacheMiss {
		k := datastore.NewKey(c, "Tag", id, 0, nil)
		if err := datastore.Get(c, k, obj); err != nil {
			return err
		}
		itemCache := &memcache.Item{
			Key:    cacheTitle,
			Object: obj,
		}
		memcache.Gob.Set(c, itemCache)
	}
	return nil
}

func TagPool(c appengine.Context) (arr []entity.Tag, err error) {
	if _, err := memcache.Gob.Get(c, TagPool_CacheName, &arr); err == memcache.ErrCacheMiss {
		q := datastore.NewQuery("Tag").Order("-doc").Limit(20)
		if _, err := q.GetAll(c, &arr); err != nil {
			return arr, err
		}
		itemCache := &memcache.Item{
			Key:    TagPool_CacheName,
			Object: arr,
		}
		memcache.Gob.Set(c, itemCache)
	}
	return arr, nil
}

func ListTagRelationshipByTagAlias(c appengine.Context, alias string, page int) (arr []entity.TagRelationship, err error) {
	page = page - 1
	q := datastore.NewQuery("TagRelationship").Filter("tagAlias =", alias).Order("tagAlias").Limit(NewsLimit + 1).Offset(NewsLimit * page)
	if _, err := q.GetAll(c, &arr); err != nil {
		return arr, err
	}
	return arr, nil
}

func CheckExistTag(c appengine.Context, id string) bool {
	k := datastore.NewKey(c, "Tag", id, 0, nil)
	if err := datastore.Get(c, k, nil); err == datastore.ErrNoSuchEntity {
		return false
	} else {
		return true
	}
}
